<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./vue.js"></script>
</head>

<body>
    <div id="app">
        <!-- number 限制输入 -->
        <input type="text" v-model.number="seach">
        <button @click="order=1">点击升序</button>
        <button @click="order=-1">点击降序</button>
        <ul>
            <li v-for="(item, index) in newPerson" :key="item.id">
                {{item.name}}---{{item.age}}
            </li>
        </ul>
    </div>
    <script>
        Vue.config.productionTip = false;
        const vm = new Vue({
            el: "#app",
            data() {
                return {
                    person: [
                        { id: "001", name: "lucy", age: 22 },
                        { id: "002", name: "lili", age: 12 },
                        { id: "003", name: "yuehan", age: 31 },
                        { id: "004", name: "liming", age: 18 },
                        { id: "005", name: "xiaowang", age: 4 },
                        { id: "006", name: "zhangsan", age: 19 },
                        { id: "007", name: "wangwu", age: 40 },
                    ],
                    // newPerson: [],
                    seach: 0,
                    order: 0
                };
            },
            //  排序也可以使用computed实现
            computed: {
                //  做数据筛查时,原数据不能直接修改,因为修改后无法还原
                // 所以使用计算属性计算出一个对象的数组供其渲染,
                newPerson() {
                    //  先筛选
                    let newPerson = this.person.filter(item => {
                        //  当seach修改时,会直接触发函数
                        return item.age > this.seach
                    })
                    //再排序
                    return newPerson.sort((a, b) => {
                        return this.order > 0 ? (a.age - b.age) : (b.age - a.age)
                    })
                }
            }

            // 该方法也可以使用watch实现 
            // watch: {
            //     seach: {
            //         immediate: true,
            //         handler(newVal) {
            //             this.newPerson = this.person.filter(item => {
            //                 return item.age > newVal
            //             })
            //         }
            //     },
            //     order: {
            //         handler(newVal) {
            //             // sort会修改原数组
            //             this.newPerson.sort((a, b) => {
            //                 return newVal > 0 ? (a.age - b.age) : (b.age - a.age)
            //             })
            //         }
            //     }
            // }
        });
    </script>
</body>

</html>